"""
核验路由
创建时间：2025-09-12
作者：开发团队
目的：处理二维码核验相关API路由
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from datetime import datetime, timezone

from ..core.database import get_db
from ..services.verification_service import (
    verify_qr_code, submit_verification_result, 
    get_verification_records, get_verification_record_by_id
)

from ..services.statistics_service import get_today_statistics


from ..schemas.verification import (
    QrCodeVerificationRequest, QrCodeVerificationResponse,
    VerificationSubmitRequest, VerificationRecordResponse,
    VerificationRecordDetailResponse
)
from ..utils.logger import get_logger

# 创建路由实例
router = APIRouter(prefix="/verification", tags=["核验"])

# 获取日志记录器
logger = get_logger(__name__)


@router.post("/qr-code", response_model=QrCodeVerificationResponse)
async def verify_qr_code_endpoint(
    request: QrCodeVerificationRequest,
    db: Session = Depends(get_db)
):
    """
    二维码核验
    :param request: 二维码核验请求
    :param db: 数据库会话
    :return: 核验结果和访客信息
    """
    try:
        result = verify_qr_code(db, request.qr_data, request.guard_id)
        return result
    except ValueError as e:
        logger.error(f"二维码核验失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"二维码核验异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.post("/submit", response_model=dict)
async def submit_verification(
    request: VerificationSubmitRequest,
    db: Session = Depends(get_db)
):
    """
    提交核验结果
    :param request: 核验结果提交请求
    :param db: 数据库会话
    :return: 提交结果
    """
    try:
        record_id = submit_verification_result(
            db, request.qr_data, request.guard_id, 
            request.result, request.notes
        )
        return {"record_id": record_id, "message": "核验结果提交成功"}
    except ValueError as e:
        logger.error(f"提交核验结果失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"提交核验结果异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/records")
async def get_records(
    skip: int = 0,
    limit: int = 20,
    db: Session = Depends(get_db)
):
    """
    获取核验记录列表
    :param skip: 跳过的记录数
    :param limit: 返回的记录数
    :param db: 数据库会话
    :return: 核验记录列表
    """
    try:
        records, total = get_verification_records(db, skip, limit)
        # 将VerificationRecord对象转换为VerificationRecordResponse对象
        record_responses = [
            VerificationRecordResponse(
                id=getattr(record, 'id'),
                visitor_name=getattr(record, 'visitor_name'),
                visitor_phone=getattr(record, 'visitor_phone'),
                host_name=getattr(record, 'host_name'),
                verification_time=getattr(record, 'verification_time'),
                result=getattr(record, 'result'),
                is_special=getattr(record, 'is_special'),
                special_type=getattr(record, 'special_type')
            )
            for record in records
        ]
        return {
            "code": 200,
            "message": "success",
            "data": {
                "items": record_responses,
                "total": total,
                "page": skip // limit + 1 if limit > 0 else 1,
                "size": limit
            },
            "timestamp": datetime.now(timezone.utc).isoformat()
        }
    except Exception as e:
        logger.error(f"获取核验记录列表异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/records/{record_id}", response_model=VerificationRecordDetailResponse)
async def get_record_detail(
    record_id: int,
    db: Session = Depends(get_db)
):
    """
    获取核验记录详情
    :param record_id: 记录ID
    :param db: 数据库会话
    :return: 核验记录详情
    """
    try:
        record = get_verification_record_by_id(db, record_id)
        if not record:
            raise HTTPException(status_code=404, detail="记录未找到")
        return record
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取核验记录详情异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/today-statistics")
async def get_today_statistics_endpoint(
    guard_id: int | None = None,
    db: Session = Depends(get_db)
):
    """
    获取今日统计数据
    :param guard_id: 门卫ID（可选）
    :param db: 数据库会话
    :return: 今日统计数据
    """
    try:
        stats = get_today_statistics(db, guard_id)
        return {
            "code": 200,
            "message": "success",
            "data": stats,
            "timestamp": datetime.now(timezone.utc).isoformat()
        }
    except Exception as e:
        logger.error(f"获取今日统计数据异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc).isoformat()
        }